//
//  StoreKitTool.swift
//  Muse
//
//  Created by oneselfGuess on 2023/5/5.
//

import Foundation
import SwiftyStoreKit
import StoreKit

enum StoreKitResult<T> {
    case success(T)
    case failure(StoreKitToolError)
    
    var data: T? {
        switch self {
            case .success(let data): return data
        default: return nil
        }
    }
    
    var errorCode: Int {
        switch self {
            case .failure(let error): return error.errorCode
        default: return 0
        }
    }
    
    var errorDesc: String {
        switch self {
            case .failure(let error): return error.errorDesc
        default: return ""
        }
    }
    
}

struct StoreKitToolError: Error {
    
    var errorCode: Int = 0
    
    var errorDesc: String = ""
    
}

struct StoreKitTool {
    
//    static func fetchReceipt() async -> StoreKitResult<String> {
//        return await withCheckedContinuation({ continuation in
//            SwiftyStoreKit.fetchReceipt(forceRefresh: true) { result in
//                switch result {
//                case .success(let receiptData):
//                    let encryptedReceipt = receiptData.base64EncodedString(options: [])
//                    continuation.resume(returning: .success(encryptedReceipt))
//                case .error(let error):
//                    print("Fetch receipt failed: \(error)")
//                    continuation.resume(returning: .failure(StoreKitToolError(errorCode: 0, errorDesc: error.localizedDescription)))
//                }
//            }
//        })
//    }
    
//    static func restore(userName: String) async -> StoreKitResult<(String?, Purchase)> {
//        return await withCheckedContinuation({ continuation in
//            SwiftyStoreKit.restorePurchases(atomically: false, applicationUsername: userName) { results in
//                ToastTool.dismiss()
//                if results.restoreFailedPurchases.count > 0 {
////                    print("Restore Failed: \(results.restoreFailedPurchases)")
//                    "Restore Failed".toast_error
//                }
//                else if results.restoredPurchases.count > 0 {
//                    for purchase in results.restoredPurchases {
//                        Task {
//                            let result = await StoreKitTool.fetchReceipt()
//                            continuation.resume(returning: .success((result.data, purchase)))
//                        }
//                    }
//                    print("Restore Success: \(results.restoredPurchases)")
//                }else {
//                    print("Nothing to Restore")
//                    continuation.resume(returning: .failure(StoreKitToolError(errorCode: 0, errorDesc: "Nothing to Restore")))
//                }
//            }
//        })
//    }
    
//    static func fetchProducts(purchaseID: String) async -> StoreKitResult<SKProduct> {
//        return await withCheckedContinuation({ continuation in
//            SwiftyStoreKit.retrieveProductsInfo([purchaseID]) { result in
//                if let product = result.retrievedProducts.first {
//                    continuation.resume(returning: .success(product))
//                }else if let invalidProductId = result.invalidProductIDs.first {
//                    "Invalid product identifier: \(invalidProductId)".toast_error
//                    ToastTool.dismiss()
//                }else {
//                    result.error?.localizedDescription.toast_error
//                    ToastTool.dismiss()
//                }
//            }
//        })
//    }
    
//    static func purchaseProduct(purchaseID: String, orderNo: String) async -> StoreKitResult<(PurchaseDetails, String?)> {
//        return await withCheckedContinuation({ continuation in
//            SwiftyStoreKit.purchaseProduct(purchaseID, atomically: false) { result in
//                switch result {
//                case .success(let product):
////                    Task {
////                        let result = await StoreKitTool.fetchReceipt()
////                        continuation.resume(returning: .success((product, result.data)))
////                    }
//                    break
//                case .error(let error):
//                    ToastTool.dismiss()
//                    switch error.code {
//                    case .unknown: "Unknown error. Please contact support".toast_error
//                    case .clientInvalid: "Not allowed to make the payment".toast_error
//                    case .paymentCancelled:  "Cancel".toast_error
//                    case .paymentInvalid: "The purchase identifier was invalid".toast_error
//                    case .paymentNotAllowed: "The device is not allowed to make the payment".toast_error
//                    case .storeProductNotAvailable: "The product is not available in the current storefront".toast_error
//                    case .cloudServicePermissionDenied: "Access to cloud service information is not allowed".toast_error
//                    case .cloudServiceNetworkConnectionFailed: "Could not connect to the network".toast_error
//                    case .cloudServiceRevoked: "User has revoked permission to use this cloud service".toast_error
//                    default: (error as NSError).localizedDescription.toast_error
//                    }
//                    continuation.resume(returning: .failure(StoreKitToolError(errorCode: error.errorCode, errorDesc: error.localizedDescription)))
//                }
//            }
//        })
//    }
    
}
